import React, { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { Spin } from 'antd';

// 懒加载页面组件
const HomePage = lazy(() => import('../pages/Home'));
const HotelListPage = lazy(() => import('../pages/HotelList'));
const HotelDetailPage = lazy(() => import('../pages/HotelDetail'));
const OrderPage = lazy(() => import('../pages/Order'));
const OrderDetailPage = lazy(() => import('../pages/OrderDetail'));
const ProfilePage = lazy(() => import('../pages/Profile'));
const ContactsPage = lazy(() => import('../pages/Contacts'));
const FavoritesPage = lazy(() => import('../pages/Favorites'));
const CouponsPage = lazy(() => import('../pages/Coupons'));
const LoginPage = lazy(() => import('../pages/Login'));
const RegisterPage = lazy(() => import('../pages/Register'));
const NotFoundPage = lazy(() => import('../pages/NotFound'));

// 路由加载中显示的组件
const LoadingComponent = () => (
  <div style={{ 
    display: 'flex', 
    justifyContent: 'center', 
    alignItems: 'center', 
    height: '100vh' 
  }}>
    <Spin size="large" tip="页面加载中..." />
  </div>
);

// 需要登录才能访问的路由
const PrivateRoute = ({ children }: { children: React.ReactNode }) => {
  // 假设从localStorage获取用户登录状态
  const isLoggedIn = localStorage.getItem('token') !== null;
  
  // 如果未登录，重定向到登录页
  if (!isLoggedIn) {
    return <Navigate to="/login" />;
  }
  
  return <>{children}</>;
};

const AppRouter = () => {
  return (
    <BrowserRouter>
      <Suspense fallback={<LoadingComponent />}>
        <Routes>
          {/* 公共路由 */}
          <Route path="/" element={<HomePage />} />
          <Route path="/hotels" element={<HotelListPage />} />
          <Route path="/hotel/:id" element={<HotelDetailPage />} />
          <Route path="/login" element={<LoginPage />} />
          <Route path="/register" element={<RegisterPage />} />
          
          {/* 需要登录的路由 */}
          <Route path="/order" element={
            <PrivateRoute>
              <OrderPage />
            </PrivateRoute>
          } />
          <Route path="/order/:id" element={
            <PrivateRoute>
              <OrderDetailPage />
            </PrivateRoute>
          } />
          <Route path="/profile" element={
            <PrivateRoute>
              <ProfilePage />
            </PrivateRoute>
          } />
          <Route path="/contacts" element={
            <PrivateRoute>
              <ContactsPage />
            </PrivateRoute>
          } />
          <Route path="/favorites" element={
            <PrivateRoute>
              <FavoritesPage />
            </PrivateRoute>
          } />
          <Route path="/coupons" element={
            <PrivateRoute>
              <CouponsPage />
            </PrivateRoute>
          } />
          
          {/* 404页面 */}
          <Route path="*" element={<NotFoundPage />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
};

export default AppRouter; 